package org.hackystat.installer.gears.model;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * Class: DownloadManager Description: The DownloadManager class's purpose is to
 * facilitate the gathering and integration of the disparate pieces of the
 * hackystat system, and to automate building them into one cohesive unit.
 * 
 * @author Josh
 * 
 */
public class DownloadManager {

	private String sensorBaseUrlString = "http://hackystat-sensorbase-uh.googlecode.com:80/files/hackystat-sensorbase-uh-8.0.1002.zip";
	private String sensorBaseDestination = "C:\\Hackystat\\Test\\SensorBase\\";
	private String sensorBaseName = "hackystat-sensorbase-uh-8.0.1002.zip";

	/**
	 * Method: DownloadManager Description: Empty constructor.
	 */
	public DownloadManager() {
		// Empty Constructor
	}

	/**
	 * Method: getSensorBaseZipFile Description: Parameters: Null Returns: Null
	 */
	public String getSensorBaseZipFile() {
		try {
			URL url = new URL(this.sensorBaseUrlString);
			System.out.println("Opening connection to "
					+ this.sensorBaseUrlString + "...");
			URLConnection urlC = url.openConnection();
			System.out.println("Permission Connection Settings: "
					+ urlC.getPermission().toString());

			// Copy resource to local file, use remote file
			// if no local file name specified
			InputStream is = url.openStream();

			// Print info about resource
			System.out
					.print("Copying resource (type: " + urlC.getContentType());
			Date date = new Date(urlC.getLastModified());
			System.out.println(", modified on: " + date.toString() + ")...");
			System.out.flush();

			File file = new File(this.sensorBaseDestination
					+ this.sensorBaseName);
			// Create file if it does not exist
			boolean success = file.createNewFile();
			if (success) {
				System.out.println(this.sensorBaseDestination
						+ this.sensorBaseName + " was created");
			} else {
				System.out.println(this.sensorBaseDestination
						+ this.sensorBaseName + " already exists!");
			}

			FileOutputStream fos = new FileOutputStream(
					this.sensorBaseDestination + this.sensorBaseName);

			int oneChar, count = 0;
			while ((oneChar = is.read()) != -1) {
				fos.write(oneChar);
				count++;
			}

			is.close();
			fos.close();
			System.out.println(count + " byte(s) copied");

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this.sensorBaseDestination + this.sensorBaseName;
	}

	/**
	 * Name: unzipSensorBase2 Description: Parameters: None Returns: Nothing
	 */
	public void unzipSensorBase() {
		Enumeration e;
		int BUFFER = 2048;
		BufferedOutputStream dest = null;
		BufferedInputStream is = null;
		ZipEntry entry;
		File unzipDestinationDirectory = new File(this.sensorBaseDestination);

		try {
			ZipFile zipfile = new ZipFile(this.sensorBaseDestination
					+ this.sensorBaseName);
			e = zipfile.entries();
			System.out.println("Extracting ... ");
			while (e.hasMoreElements()) {
				entry = (ZipEntry) e.nextElement();

				if (entry.isDirectory()) {
					System.out.println("Creating directory " + entry.getName());
					File destFile = new File(unzipDestinationDirectory, entry
							.getName());
					// File destinationParent = destFile.getParentFile();
					destFile.mkdirs();
				}

				else if (!entry.isDirectory()) {
					System.out.println("Unzipping file " + entry.getName());
					is = new BufferedInputStream(zipfile.getInputStream(entry));
					int count;
					byte data[] = new byte[BUFFER];
					FileOutputStream fos = new FileOutputStream(
							this.sensorBaseDestination + entry.getName());
					dest = new BufferedOutputStream(fos, BUFFER);
					while ((count = is.read(data, 0, BUFFER)) != -1) {
						dest.write(data, 0, BUFFER);
					}
					dest.flush();
					dest.close();
					is.close();
				}
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/**
	 * Method: RegisterEnvVariables Description: Parameters: Returns:
	 */
	public void RegisterEnvVariables() {
		HashMap<String, Double> sysEvnVariables = new HashMap<String, Double>();

		try {
			String sysEnvJavaHome = System.getenv("JAVA_HOME");
			
			
			if (sysEnvJavaHome == null) {
				sysEnvJavaHome = "0.0";
			}

			double javaVersion = 0.0;

			javaVersion = verifyJavaVersion(sysEnvJavaHome);

			if (javaVersion < 1.6) {
				System.out
						.println("Please upgrade your version of java to 1.6");
			}
			sysEvnVariables.put("JAVA_HOME", javaVersion);
			
			
		} catch (SecurityException se) {
			System.out
					.println("Security Exception trying to access Environmental Variable");
		}

	}

	/**
	 * Method: verifyJavaVersion Description: Verifies the current java version.
	 * Must be java 1.5 or higher.
	 * 
	 * @param javaHome
	 */
	public double verifyJavaVersion(String javaHome) {
		int versionIndex = javaHome.lastIndexOf("\\", javaHome.length());
		double javaVersionDbl;
		String javaVersionStr = javaHome.substring(versionIndex + 4,
				versionIndex + 7);
		javaVersionDbl = Double.parseDouble(javaVersionStr);
		return javaVersionDbl;
	}

}
